﻿#include "curlUtils.h"
#include "stream/hnstring.h"
#include <iostream>
#include <fstream>
#include <stream/hnuuid.h>

UrlObeject::UrlObeject(const char* url, const char* path) :size(0)
{
    this->url = url;
    this->filePath = path;
    uuid = UUIDUtils::GenerateUUID();
}
namespace HNNetwork {


    // 回调函数，用于保存下载的数据
    size_t WriteCallback(void* contents, size_t size, size_t nmemb, void* userp)
    {
        std::ofstream* file = static_cast<std::ofstream*>(userp);
        file->write(static_cast<const char*>(contents), (std::streamsize)(size * nmemb));
        return (size * nmemb);
    }

    void MessageCallbackThread(const std::string& url, long threadID, int status, const char* msg)
    {
        switch (status)
        {
        case CURLcode::CURLE_OK:
            break;

        }
        std::cout << "Thread " << threadID << ",Url:" << url << ", 错误代码: " << status << "-" << msg << std::endl;
    }
    bool CheckUrlCode(CURL* curl, const char* url, CURLcode status)
    {
        switch (status)
        {
        case CURLcode::CURLE_OK:
            return true;

        }
        std::cout << url << ", 错误代码: " << status << "-" << curl_easy_strerror(status) << std::endl;
        curl_easy_cleanup(curl);
        return false;
    }
    bool JustCheckUrlCode(CURL* curl, const char* url, CURLcode status)
    {
        switch (status)
        {
        case CURLcode::CURLE_OK:
            return true;

        }
        std::cout << url << ", 错误代码: " << status << "-" << curl_easy_strerror(status) << std::endl;
        return false;
    }

    // 获取需要开辟的线程数量
    long getThreadCount(long size, long curFlow)
    {
        LIMITMAX(curFlow, MAXFLOW);
        LIMITMIN(curFlow, MINFLOW);
        long count = std::ceil(size / curFlow);
        if (count > 512) 
        {
            count =512;
        }
        return count;
        //return (((count) < (MAXTHREADCOUNT)) ? (count) : (MAXTHREADCOUNT));
    }
    std::string getNetworkRate(long size_bits, long time_ms) 
    {
        float time_s = time_ms / 1000.0;
        float size_kb = size_bits / (float)MAX1024;
        return floatToStringWithTwoDecimalPlaces(size_kb / time_s, 2) + " kb/s";
    }

    std::string convertDataSize(long size)
    {
        float dataSize = size / (float)MAX1024;
        if (dataSize < MAX1024)
        {
            return floatToStringWithTwoDecimalPlaces(dataSize, 2) + " KB";
        }
        dataSize /= (float)MAX1024;
        if (dataSize < MAX1024)
        {
            return floatToStringWithTwoDecimalPlaces(dataSize, 2) + " MB";
        }
        dataSize /= (float)MAX1024;
        if (dataSize < MAX1024)
        {
            return floatToStringWithTwoDecimalPlaces(dataSize, 2) + " GB";
        }
        dataSize /= (float)MAX1024;
        return floatToStringWithTwoDecimalPlaces(dataSize, 2) + " TB";
    }
}//HNNetWork
